//////////////////////////////////////////////////////////////////////////
#include <RocketLua/RocketLua.hpp>


using namespace Rocket::Core::Lua;


//////////////////////////////////////////////////////////////////////////
LuaDocument::LuaDocument( lua_State* state, const Rocket::Core::String& tag )
:	ElementDocument( tag )
,	mpState( state )
{
	// TODO: Figure out how to pass in document and context in a better manner.
	Rocket::Core::ElementDocument*	doc	=	this;
	luabridge::setGlobal( mpState, doc, "document" );
}


LuaDocument::~LuaDocument()
{
}


void LuaDocument::LoadScript( Rocket::Core::Stream* stream, const Rocket::Core::String& sourceName )
{
	if( sourceName != "" )
	{
		if( luaL_loadstring( mpState, sourceName.CString() ) != LUA_OK )
		{
			LOG( INFO ) << "Failed to load: \n" << sourceName.CString();
			return;
		}

		if( lua_pcall( mpState, 0, 1, 0 ) != LUA_OK )
		{
			LOG( INFO ) << "Failed to compile: \n" << sourceName.CString();
			return;
		}

		LOG( INFO ) << "Loaded: \n" << sourceName.CString();
	}
	else
	{
		String	buffer	=	"";
		stream->Read( buffer, stream->Length() );

		if( luaL_loadstring( mpState, buffer.CString() ) != LUA_OK )
		{
			LOG( INFO ) << "Failed to load: \n" << buffer.CString();
			return;
		}

		if( lua_pcall( mpState, 0, 1, 0 ) != LUA_OK )
		{
			LOG( INFO ) << "Failed to compile: \n" << buffer.CString();
			return;
		}

		LOG( INFO ) << "Loaded: \n" << buffer.CString();
	}
}


int LuaDocument::luaGetElementById( lua_State* state, ElementDocument* doc )
{
	int	result	=	0;
	if( lua_isstring( state, -1 ) )
	{
		Rocket::Core::Element*	elp	=	doc->GetElementById( lua_tostring( state, -1 ) );
		luabridge::LuaRef	ele( state, elp );
		if( ele )
			ele.push( state );
		else
			lua_pushnil( state );
		result	=	1;
	}

	return result;
}


void LuaDocument::Register( lua_State* state )
{
	luabridge::getGlobalNamespace( state )
		.beginClass< Rocket::Core::ElementDocument >( "Document" )
			.addFunction( "PullToFront", &ElementDocument::PullToFront )
			.addFunction( "PushToBack", &ElementDocument::PushToBack )
			.addFunction( "Show", &ElementDocument::Show )
			.addFunction( "Hide", &ElementDocument::Hide )
			.addFunction( "Close", &ElementDocument::Close )
			.addCFunction< Rocket::Core::ElementDocument >( "GetElementById", &LuaDocument::luaGetElementById )
		.endClass();
}
